package br.edu.sistemaacademico;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.ListSelectionModel;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import javax.swing.table.DefaultTableModel;

import br.edu.sistemaacademico.Decorator.ConcretDecorator;
import br.edu.sistemaacademico.adapter.IMenuCadastro;
import br.edu.sistemaacademico.facade.DataFacade;
import br.edu.sistemaacademico.pojo.Aluno;
import br.edu.sistemaacademico.pojo.Classe;
import br.edu.sistemaacademico.pojo.Curso;
import br.edu.sistemaacademico.pojo.Matricula;
import br.edu.sistemaacademico.pojo.Turma;
import br.edu.sistemaacademico.state.StateHandler;
import client.ClientCommand;


public class frmFecharTurma extends IMenuCadastro {
	Aluno aluno;
	Matricula matricula;
	Curso curso;
	 public List<Object> campos = ClientCommand.getCampos("CursoService");//new ArrayList<Object>();
	    private List<Object> valores = new ArrayList<Object>();
	    private List<Object> tamanho = new ArrayList<Object>();
	    TabelaModelo tabModel;
	    List<Curso> extra;
	    List<Matricula> matriculas;
	    ConcretDecorator cc = null;
	    
    public frmFecharTurma(Aluno aluno) {
        initComponents();
        this.aluno = aluno;
        tabModel = new TabelaModelo(campos, tamanho, jTable1);
        if (cc==null)
            cc = new ConcretDecorator(this);
        ListSelectionModel listModel = jTable1.getSelectionModel();
        listModel.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        listModel.addListSelectionListener(list);
        atualiza();
        setButtons();
        cc.setVisible(true);
    }

    @SuppressWarnings("unchecked")
    private void initComponents() {
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();

        jButton1.setText("Cancelar");
        jButton1.setName("jButton1"); // NOI18N

        jButton2.setText("Cadastrar");
        jButton2.setName("jButton2"); // NOI18N

        jScrollPane1.setName("jScrollPane1"); // NOI18N

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jTable1.setName("jTable1"); // NOI18N
        jScrollPane1.setViewportView(jTable1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jButton2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 175, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addContainerGap())
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 525, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(13, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 393, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1)
                    .addComponent(jButton2)))
        );
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    // End of variables declaration//GEN-END:variables
    
    public void setButtons(){
    	ActionListener listener = new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if(e.getSource()==jButton2){
				operacao();
				atualiza();
				}else
					cc.dispose();
			}
		};
		jButton2.addActionListener(listener);
		jButton1.addActionListener(listener);
    }

    public void atualiza(){
    	((DefaultTableModel) jTable1.getModel()).setNumRows(0);
    	jTable1.updateUI();
    	matriculas = (List) ClientCommand.carregar("MatriculaService", "aluno="+aluno.getId(), "");
    	StringBuilder condicao = new StringBuilder("codigo not in(");
		if(matriculas.size()==0)
			condicao.append("0");
		else
		for(int i =0;i<matriculas.size();i++){
			if(i <= matriculas.size()-1&&i>0){
				if(matriculas.get(i).getCurso().getId()==null)
					condicao.append("0");
				else
				condicao.append(","+matriculas.get(i).getCurso().getId());
			}else{
				if(matriculas.get(i).getCurso().getId()==null)
					condicao.append("0");
				else
				condicao.append(matriculas.get(i).getCurso().getId());
			}
		}
		condicao.append(")");
    	extra = (List)ClientCommand.carregar("CursoService",condicao.toString(), "");
    	for(int i = 0; i < extra.size();i++ ){
    		valores = new LinkedList<Object>();
    		valores.add(extra.get(i).getId());
    		valores.add(extra.get(i).getNome());
    		valores.add(extra.get(i).getAnoRegulamentado());
    		tabModel.setValores(valores);
    		valores.clear();
    	}
    }
	 ListSelectionListener list = new ListSelectionListener() {
			
			@Override
			public void valueChanged(ListSelectionEvent e) {
				try{
					if(jTable1.getSelectedRow()>=0)
				curso = getSelectedCurso(Long.parseLong(jTable1.getValueAt(jTable1.getSelectedRow(), 0).toString()));
				}catch(ArrayIndexOutOfBoundsException ea){
					curso = null;
				}
			}
		};
		
		public Curso getSelectedCurso(Long codigo){
			return (Curso) ClientCommand.carregaObjeto("CursoService", "codigo="+codigo, "");
		}
 	    
 		@Override
 		public void menuExemplo(JMenuItem item) {
 			// TODO Auto-generated method stub
 			
 		}

 		@Override
 		public void menuFechar(JMenuItem item) {
 			cc.dispose();		
 		}

 		@Override
 		public void menuLimpa(JMenuItem item) {
 					
 		}

 		@Override
 		public void menuManual(JMenuItem item) {
 			// TODO Auto-generated method stub		
 		}

 		@Override
 		public void menuMementor(JMenuItem item) {
 			// TODO Auto-generated method stub		
 		}

 		@Override
 		public void menuOperacao(JMenuItem item) {
 			item.setText("Realizar Matricula");
 			operacao();
 		}

 		@Override
 		public void menuSobre(JMenuItem item) {
 			// TODO Auto-generated method stub
 			
 		}
 	  
 	  public void operacao(){
 			DataFacade facade = new DataFacade();
			matricula = new Matricula();
			matricula.setDataMatricula(facade.getDate());
			matricula.setAluno(aluno);
			matricula.setCurso(curso);
			matricula.setEstado("regular");
			
				if(ClientCommand.gravar("MatriculaService",matricula)==true)
					JOptionPane.showMessageDialog(null, "Matricula Realizada com Sucesso");
					atualiza();
 	  }
	    
	    
	    
}
